﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Drifting.Foundation;
using Drifting.MotionPlanning.Primitives;

namespace Drifting.Graphics.EffectObjects
{
    public class Polygon2D : EffectObject
    {
        VertexPositionColor[] vertices;
        short[] indices;
        short[] indices1;
        BasicEffect effects;
        Matrix configuration;

        public Polygon2D(MotionPlanning.Systems.CollisionPrimitives.Polygon2D polygon, float scale, Color color, GraphicsDevice device)
            : base(device)
        {
            vertices = new VertexPositionColor[polygon.Vertices.Count];
            indices = new short[vertices.Length];
            indices1 = new short[vertices.Length];
            for (int i = 0; i < vertices.Length; ++i)
            {
                double[] coord = polygon.Vertices[i];
                vertices[i] = new VertexPositionColor(new Vector3((float)coord[0], 0, (float)coord[1]), color);
                indices[i] = (short)i;
            }
            for (int i = 0; i < vertices.Length; ++i)
                indices1[i] = (short)(i + 1);
            indices1[indices1.Length - 1] = 0;

            effects = new BasicEffect(device);

            configuration = Matrix.CreateRotationY((float)polygon.Orientation) * Matrix.CreateTranslation((float)polygon.X, 0, (float)polygon.Y);
        }

        public void Draw(Matrix view, Matrix projection, Matrix config)
        {
            effects.VertexColorEnabled = true;
            effects.World = config;
            effects.View = view;
            effects.Projection = projection;
            effects.CurrentTechnique.Passes[0].Apply();

            device.DrawUserIndexedPrimitives<VertexPositionColor>(PrimitiveType.TriangleStrip, vertices, 0, vertices.Length, indices1, 0, indices1.Length - 2);
            device.DrawUserIndexedPrimitives<VertexPositionColor>(PrimitiveType.TriangleStrip, vertices, 0, vertices.Length, indices, 0, indices.Length - 2);
        }

        override public void Draw(Matrix view, Matrix projection)
        {
            effects.VertexColorEnabled = true;
            effects.World = configuration;
            effects.View = view;
            effects.Projection = projection;
            effects.CurrentTechnique.Passes[0].Apply();

            device.DrawUserIndexedPrimitives<VertexPositionColor>(PrimitiveType.TriangleStrip, vertices, 0, vertices.Length, indices1, 0, indices1.Length - 2);
            device.DrawUserIndexedPrimitives<VertexPositionColor>(PrimitiveType.TriangleStrip, vertices, 0, vertices.Length, indices, 0, indices.Length - 2);
        }
    }
}
